<!doctype html>



  


<html class="theme-next pisces use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="SpringBoot,Zookeeper," />





  <link rel="alternate" href="/atom.xml" title="crossoverJie's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="背景最近在做分布式相关的工作，由于人手不够只能我一个人来怼；看着这段时间的加班表想想就是够惨的。
不过其中也有遇到的不少有意思的事情今后再拿来分享，今天重点来讨论服务的注册与发现。
分布式带来的问题我的业务比较简单，只是需要知道现在有哪些服务实例可供使用就可以了（并不是做远程调用，只需要拿到信息即可）。
要实现这一功能最简单的方式可以在应用中配置所有的服务节点，这样每次在使用时只需要通过某种算法">
<meta property="og:type" content="article">
<meta property="og:title" content="分布式(一) 搞定服务注册与发现">
<meta property="og:url" content="http://crossoverjie.top/2018/08/27/distributed/distributed-discovery-zk/index.html">
<meta property="og:site_name" content="crossoverJie's Blog">
<meta property="og:description" content="背景最近在做分布式相关的工作，由于人手不够只能我一个人来怼；看着这段时间的加班表想想就是够惨的。
不过其中也有遇到的不少有意思的事情今后再拿来分享，今天重点来讨论服务的注册与发现。
分布式带来的问题我的业务比较简单，只是需要知道现在有哪些服务实例可供使用就可以了（并不是做远程调用，只需要拿到信息即可）。
要实现这一功能最简单的方式可以在应用中配置所有的服务节点，这样每次在使用时只需要通过某种算法">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d22474b79.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d22a0ab9f.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d22aa8afa.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d22b37597.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d22ba62d5.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d22d1fd47.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d22ed3d2f.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d2353b899.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d235d30ea.jpg">
<meta property="og:image" content="https://i.loli.net//2019//05//08//5cd1dc84306df.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d2b5b15fd.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d2b66b2b2.jpg">
<meta property="og:image" content="https://i.loli.net//2019//05//08//5cd1dd090d37e.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d4faa9cfc.jpg">
<meta property="og:image" content="https://i.loli.net//2019//05//08//5cd1dd8cc097a.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d52ed5080.jpg">
<meta property="og:updated_time" content="2019-05-07T19:35:27.290Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="分布式(一) 搞定服务注册与发现">
<meta name="twitter:description" content="背景最近在做分布式相关的工作，由于人手不够只能我一个人来怼；看着这段时间的加班表想想就是够惨的。
不过其中也有遇到的不少有意思的事情今后再拿来分享，今天重点来讨论服务的注册与发现。
分布式带来的问题我的业务比较简单，只是需要知道现在有哪些服务实例可供使用就可以了（并不是做远程调用，只需要拿到信息即可）。
要实现这一功能最简单的方式可以在应用中配置所有的服务节点，这样每次在使用时只需要通过某种算法">
<meta name="twitter:image" content="https://i.loli.net/2019/05/08/5cd1d22474b79.jpg">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 555390,
      author: 'crossoverJie'
    }
  };
</script>




  <link rel="canonical" href="http://crossoverjie.top/2018/08/27/distributed/distributed-discovery-zk/"/>

  <title> 分布式(一) 搞定服务注册与发现 | crossoverJie's Blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  








  <div style="display: none;">
    <script src="https://s6.cnzz.com/stat.php?id=1259025147&web_id=1259025147" type="text/javascript"></script>
  </div>





  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">crossoverJie's Blog</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">baller</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            About
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-photo">
          <a href="/favourite" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-photo"></i> <br />
            
            photo
          </a>
        </li>
      
        
        <li class="menu-item menu-item-jcsprout">
          <a href="https://crossoverjie.top/JCSprout/#/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-leaf"></i> <br />
            
            JCSprout
          </a>
        </li>
      
        
        <li class="menu-item menu-item-cicada">
          <a href="https://github.com/TogetherOS/cicada" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-github"></i> <br />
            
            cicada
          </a>
        </li>
      
        
        <li class="menu-item menu-item-cim">
          <a href="https://github.com/crossoverjie/cim" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-far fa-comment"></i> <br />
            
            CIM
          </a>
        </li>
      
        
        <li class="menu-item menu-item-vlog">
          <a href="https://space.bilibili.com/42339430" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-youtube"></i> <br />
            
            Vlog
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="#" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                分布式(一) 搞定服务注册与发现
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">Posted on</span>
            <time itemprop="dateCreated" datetime="2018-08-27T00:10:36+08:00" content="2018-08-27">
              2018-08-27
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">In</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/Distributed/" itemprop="url" rel="index">
                    <span itemprop="name">Distributed</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2018/08/27/distributed/distributed-discovery-zk/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2018/08/27/distributed/distributed-discovery-zk/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          
             <span id="/2018/08/27/distributed/distributed-discovery-zk/" class="leancloud_visitors" data-flag-title="分布式(一) 搞定服务注册与发现">
               &nbsp; | &nbsp;
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">visitors </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          
              &nbsp; | &nbsp;
              <span class="page-pv">本文总阅读量
              <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
              </span>
          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="https://i.loli.net/2019/05/08/5cd1d22474b79.jpg" alt=""></p>
<h2 id="背景"><a href="#背景" class="headerlink" title="背景"></a>背景</h2><p>最近在做分布式相关的工作，由于人手不够只能我一个人来怼；看着这段时间的加班表想想就是够惨的。</p>
<p>不过其中也有遇到的不少有意思的事情今后再拿来分享，今天重点来讨论服务的<strong>注册与发现</strong>。</p>
<h2 id="分布式带来的问题"><a href="#分布式带来的问题" class="headerlink" title="分布式带来的问题"></a>分布式带来的问题</h2><p>我的业务比较简单，只是需要知道现在有哪些服务实例可供使用就可以了（并不是做远程调用，只需要拿到信息即可）。</p>
<p>要实现这一功能最简单的方式可以在应用中配置所有的服务节点，这样每次在使用时只需要通过某种算法从配置列表中选择一个就可以了。</p>
<p>但这样会有一个非常严重的问题：</p>
<p>由于应用需要根据应用负载情况来灵活的调整服务节点的数量，这样我的配置就不能写死。</p>
<p>不然就会出现要么新增的节点没有访问或者是已经 down 掉的节点却有请求，这样肯定是不行的。</p>
<p>往往要解决这类分布式问题都需要一个公共的区域来保存这些信息，比如是否可以利用 Redis？</p>
<p>每个节点启动之后都向 Redis 注册信息，关闭时也删除数据。</p>
<p>其实就是存放节点的 <code>ip + port</code>，然后在需要知道服务节点信息时候只需要去 Redis 中获取即可。</p>
<a id="more"></a>
<p>如下图所示：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d22a0ab9f.jpg" alt=""></p>
<p>但这样会导致每次使用时都需要频繁的去查询 Redis，为了避免这个问题我们可以在每次查询之后在本地缓存一份最新的数据。这样优先从本地获取确实可以提高效率。</p>
<p>但同样又会出现新的问题，如果服务提供者的节点新增或者删除消费者这边根本就不知道情况。</p>
<p>要解决这个问题最先想到的应该就是利用定时任务定期去更新服务列表。</p>
<p>以上的方案肯定不完美，并且不优雅。主要有以下几点：</p>
<ul>
<li>基于定时任务会导致很多无效的更新。</li>
<li>定时任务存在周期性，没法做到实时，这样就可能存在请求异常。</li>
<li>如果服务被强行 kill，没法及时清除 Redis，这样这个看似可用的服务将永远不可用！</li>
</ul>
<p>所以我们需要一个更加靠谱的解决方案，这样的场景其实和 Dubbo 非常类似。</p>
<p>用过的同学肯定对这张图不陌生。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d22aa8afa.jpg" alt=""></p>
<blockquote>
<p>引用自 Dubbo <a href="https://dubbo.incubator.apache.org/en-us/" target="_blank" rel="external">官网</a></p>
</blockquote>
<p>其中有一块非常核心的内容（红框出）就是服务的注册与发现。</p>
<p>通常来说消费者是需要知道服务提供者的网络地址(ip + port)才能发起远程调用，这块内容和我上面的需求其实非常类似。</p>
<p>而 Dubbo 则是利用 Zookeeper 来解决问题。</p>
<h2 id="Zookeeper-能做什么"><a href="#Zookeeper-能做什么" class="headerlink" title="Zookeeper 能做什么"></a>Zookeeper 能做什么</h2><p>在具体讨论怎么实现之前先看看 Zookeeper 的几个重要特性。</p>
<p>Zookeeper 实现了一个类似于文件系统的树状结构：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d22b37597.jpg" alt=""></p>
<p>这些节点被称为 znode(名字叫什么不重要)，其中每个节点都可以存放一定的数据。</p>
<p>最主要的是 znode 有四种类型：</p>
<ul>
<li>永久节点（除非手动删除，节点永远存在）</li>
<li>永久有序节点（按照创建顺序会为每个节点末尾带上一个序号如：<code>root-1</code>）</li>
<li>瞬时节点（创建客户端与 Zookeeper 保持连接时节点存在，断开时则删除并会有相应的通知）</li>
<li>瞬时有序节点（在瞬时节点的基础上加上了顺序）</li>
</ul>
<p>考虑下上文使用 Redis 最大的一个问题是什么？</p>
<p>其实就是不能实时的更新服务提供者的信息。</p>
<p>那利用 Zookeeper 是怎么实现的？</p>
<p>主要看第三个特性：<strong>瞬时节点</strong></p>
<p>Zookeeper 是一个典型的观察者模式。</p>
<ul>
<li>由于瞬时节点的特点，我们的消费者可以订阅瞬时节点的父节点。</li>
<li>当新增、删除节点时所有的瞬时节点也会自动更新。</li>
<li>更新时会给订阅者发起通知告诉最新的节点信息。</li>
</ul>
<p>这样我们就可以实时获取服务节点的信息，同时也只需要在第一次获取列表时缓存到本地；也不需要频繁和 Zookeeper 产生交互，只用等待通知更新即可。</p>
<p>并且不管应用什么原因节点 down 掉后也会在 Zookeeper 中删除该信息。</p>
<h2 id="效果演示"><a href="#效果演示" class="headerlink" title="效果演示"></a>效果演示</h2><p>这样实现方式就变为这样。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d22ba62d5.jpg" alt=""></p>
<p>为此我新建了一个应用来进行演示：</p>
<p><a href="https://github.com/crossoverJie/netty-action/tree/master/netty-action-zk" target="_blank" rel="external">https://github.com/crossoverJie/netty-action/tree/master/netty-action-zk</a></p>
<p>就是一个简单的 SpringBoot 应用，只是做了几件事情。</p>
<ul>
<li>应用启动时新开一个线程用于向 Zookeeper 注册服务。</li>
<li>同时监听一个节点用于更新本地服务列表。</li>
<li>提供一个接口用于返回一个可有的服务节点。</li>
</ul>
<p>我在本地启动了两个应用分别是：<code>127.0.0.1:8083,127.0.0.1:8084</code>。来看看效果图。</p>
<p>两个应用启动完成：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d22d1fd47.jpg" alt=""></p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d22ed3d2f.jpg" alt=""></p>
<hr>
<p>当前 Zookeeper 的可视化树状结构：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d2353b899.jpg" alt=""></p>
<hr>
<p>当想知道所有的服务节点信息时：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d235d30ea.jpg" alt=""></p>
<hr>
<p>想要获取一个可用的服务节点时：</p>
<p><img src="https://i.loli.net//2019//05//08//5cd1dc84306df.jpg" alt=""></p>
<p>这里只是采取了简单的轮询。</p>
<hr>
<p>当 down 掉一个节点时：应用会收到通知更新本地缓存。同时 Zookeeper 中的节点会自动删除。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d2b5b15fd.jpg" alt=""></p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d2b66b2b2.jpg" alt=""></p>
<hr>
<p>再次获取最新节点时：</p>
<p><img src="https://i.loli.net//2019//05//08//5cd1dd090d37e.jpg" alt=""></p>
<hr>
<p>当节点恢复时自然也能获取到最新信息。本地缓存也会及时更新。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d4faa9cfc.jpg" alt=""></p>
<p><img src="https://i.loli.net//2019//05//08//5cd1dd8cc097a.jpg" alt=""></p>
<h2 id="编码实现"><a href="#编码实现" class="headerlink" title="编码实现"></a>编码实现</h2><p>实现起来倒也比较简单，主要就是 ZKClient 的 api 使用。</p>
<p>贴几段比较核心的吧。</p>
<h3 id="注册"><a href="#注册" class="headerlink" title="注册"></a>注册</h3><blockquote>
<p>启动注册 Zookeeper。</p>
</blockquote>
<p><img src="https://i.loli.net/2019/05/08/5cd1d52ed5080.jpg" alt=""></p>
<p>主要逻辑都在这个线程中。</p>
<ul>
<li>首先创建父节点。如上图的 Zookeeper 节点所示；需要先创建 <code>/route</code> 根节点，创建的时候会判断是否已经存在。</li>
<li>接着需要判断是否需要将自己注册到 Zookeeper 中，因为有些节点只是用于服务发现，他自身是不需要承担业务功能（是我自己项目的需求）。</li>
<li>将当前应用的所在 ip 以及端口注册上去，同时需要监听根节点 <code>/route</code> ，这样才能在其他服务上下线时候获得通知。</li>
</ul>
<h3 id="根据本地缓存"><a href="#根据本地缓存" class="headerlink" title="根据本地缓存"></a>根据本地缓存</h3><blockquote>
<p>监听到服务变化</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">subscribeEvent</span><span class="params">(String path)</span> </span>&#123;</div><div class="line">    zkClient.subscribeChildChanges(path, <span class="keyword">new</span> IZkChildListener() &#123;</div><div class="line">        <span class="meta">@Override</span></div><div class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">handleChildChange</span><span class="params">(String parentPath, List&lt;String&gt; currentChilds)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">            logger.info(<span class="string">"清除/更新本地缓存 parentPath=【&#123;&#125;】,currentChilds=【&#123;&#125;】"</span>, parentPath,currentChilds.toString());</div><div class="line"></div><div class="line">            <span class="comment">//更新所有缓存/先删除 再新增</span></div><div class="line">            serverCache.updateCache(currentChilds) ;</div><div class="line">        &#125;</div><div class="line">    &#125;);</div><div class="line"></div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>可以看到这里是更新了本地缓存，该缓存采用了 Guava 提供的 Cache，感兴趣的可以查看之前的<a href="https://crossoverjie.top/categories/Guava/">源码分析</a>。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> * 更新所有缓存/先删除 再新增</div><div class="line"> *</div><div class="line"> * <span class="doctag">@param</span> currentChilds</div><div class="line"> */</div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">updateCache</span><span class="params">(List&lt;String&gt; currentChilds)</span> </span>&#123;</div><div class="line">    cache.invalidateAll();</div><div class="line">    <span class="keyword">for</span> (String currentChild : currentChilds) &#123;</div><div class="line">        String key = currentChild.split(<span class="string">"-"</span>)[<span class="number">1</span>];</div><div class="line">        addCache(key);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="客户端负载"><a href="#客户端负载" class="headerlink" title="客户端负载"></a>客户端负载</h3><blockquote>
<p>同时在客户端提供了一个负载算法。</p>
</blockquote>
<p>其实就是一个轮询的实现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> * 选取服务器</div><div class="line"> *</div><div class="line"> * <span class="doctag">@return</span></div><div class="line"> */</div><div class="line"><span class="function"><span class="keyword">public</span> String <span class="title">selectServer</span><span class="params">()</span> </span>&#123;</div><div class="line">    List&lt;String&gt; all = getAll();</div><div class="line">    <span class="keyword">if</span> (all.size() == <span class="number">0</span>) &#123;</div><div class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"路由列表为空"</span>);</div><div class="line">    &#125;</div><div class="line">    Long position = index.incrementAndGet() % all.size();</div><div class="line">    <span class="keyword">if</span> (position &lt; <span class="number">0</span>) &#123;</div><div class="line">        position = <span class="number">0L</span>;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="keyword">return</span> all.get(position.intValue());</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>当然这里可以扩展出更多的如权重、随机、<a href="https://crossoverjie.top/%2F2018%2F04%2F07%2Falgorithm%2FLRU-cache%2F">LRU</a> 等算法。</p>
<h2 id="Zookeeper-其他优势及问题"><a href="#Zookeeper-其他优势及问题" class="headerlink" title="Zookeeper 其他优势及问题"></a>Zookeeper 其他优势及问题</h2><p>Zookeeper 自然是一个很棒的分布式协调工具，利用它的特性还可以有其他作用。</p>
<ul>
<li>数据变更发送通知这一特性可以实现统一配置中心，再也不需要在每个服务中单独维护配置。</li>
<li>利用瞬时有序节点还可以实现分布式锁。</li>
</ul>
<p>在实现注册、发现这一需求时，Zookeeper 其实并不是最优选。</p>
<p>由于 Zookeeper 在 CAP 理论中选择了 CP（一致性、分区容错性），当 Zookeeper 集群有半数节点不可用时是不能获取到任何数据的。</p>
<p>对于一致性来说自然没啥问题，但在注册、发现的场景下更加推荐 <code>Eureka</code>，已经在 SpringCloud 中得到验证。具体就不在本文讨论了。</p>
<p>但鉴于我的使用场景来说 Zookeeper 已经能够胜任。</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>本文所有完整代码都托管在 GitHub。</p>
<p><a href="https://github.com/crossoverJie/netty-action" target="_blank" rel="external">https://github.com/crossoverJie/netty-action</a>。</p>
<p>一个看似简单的注册、发现功能实现了，但分布式应用远远不止这些。</p>
<p>由于网络隔离之后带来的一系列问题还需要我们用其他方式一一完善；后续会继续更新分布式相关内容，感兴趣的朋友不妨持续关注。</p>
<p><strong>你的点赞与转发是最大的支持。</strong></p>

      
    </div>

    <div>
      
        
<div id="wechat_subscriber" style="display: block； padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/uploads/weixinfooter1.jpg" alt="crossoverJie wechat" style="width: 200px; max-width: 100%;"/>
    <div>我很有眼光！</div>
</div>

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>请我吃🍗</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="/weixin-reward-image.jpg" alt="crossoverJie WeChat Pay"/>
          <p>微信打赏</p>
        </div>
      
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="/alipay-reward-image.jpg" alt="crossoverJie Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/SpringBoot/" rel="tag">#SpringBoot</a>
          
            <a href="/tags/Zookeeper/" rel="tag">#Zookeeper</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/08/21/skill/resume/" rel="next" title="什么样的简历不会被丢进回收站">
                <i class="fa fa-chevron-left"></i> 什么样的简历不会被丢进回收站
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/08/29/java-senior/OOM-Disruptor/" rel="prev" title="强如 Disruptor 也发生内存溢出？">
                强如 Disruptor 也发生内存溢出？ <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  <p>热评文章</p>
  <div class="ds-top-threads" data-range="weekly" data-num-items="4"></div>


          
  <div class="comments" id="comments">
    
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            Overview
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/crossoverjie.jpg"
               alt="crossoverJie" />
          <p class="site-author-name" itemprop="name">crossoverJie</p>
          <p class="site-description motion-element" itemprop="description">You never know what you can do till you try.</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">116</span>
              <span class="site-state-item-name">posts</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">45</span>
                <span class="site-state-item-name">categories</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">109</span>
                <span class="site-state-item-name">tags</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/crossoverJie" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.jianshu.com/users/e2d07947c112/latest_articles" target="_blank" title="简书">
                  
                    <i class="fa fa-fw fa-book"></i>
                  
                  简书
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://juejin.im/user/576d4aaf7db2a20054ea4544" target="_blank" title="掘金">
                  
                    <i class="fa fa-fw fa-bookmark"></i>
                  
                  掘金
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/crossoverJie" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              友情链接
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://wuchong.me" title="Jark's Blog" target="_blank">Jark's Blog</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://tengj.top" title="嘟嘟独立博客" target="_blank">嘟嘟独立博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://yemengying.com/" title="Giraffe Home" target="_blank">Giraffe Home</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://blog.jamespan.me/" title="潘小鶸(ruò)" target="_blank">潘小鶸(ruò)</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://fangjian0423.github.io/" title="Format's Notes" target="_blank">Format's Notes</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://yuzhouwan.com/" title="Benedict Jin" target="_blank">Benedict Jin</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://blog.didispace.com/" title="程序猿DD" target="_blank">程序猿DD</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://blog.52itstyle.vip/" title="小柒博客" target="_blank">小柒博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://cmsblogs.com/" title="Java技术驿站" target="_blank">Java技术驿站</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://vim.ink/" title="vim 教程网" target="_blank">vim 教程网</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.jitwxs.cn" title="jitwxs" target="_blank">jitwxs</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.javaboy.org" title="江南一点雨" target="_blank">江南一点雨</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.liangsonghua.me" title="松花皮蛋的黑板报" target="_blank">松花皮蛋的黑板报</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.fi-ads.com" title="Future iDeal" target="_blank">Future iDeal</a>
                </li>
              
            </ul>
          </div>
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#背景"><span class="nav-number">1.</span> <span class="nav-text">背景</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#分布式带来的问题"><span class="nav-number">2.</span> <span class="nav-text">分布式带来的问题</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Zookeeper-能做什么"><span class="nav-number">3.</span> <span class="nav-text">Zookeeper 能做什么</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#效果演示"><span class="nav-number">4.</span> <span class="nav-text">效果演示</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#编码实现"><span class="nav-number">5.</span> <span class="nav-text">编码实现</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#注册"><span class="nav-number">5.1.</span> <span class="nav-text">注册</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#根据本地缓存"><span class="nav-number">5.2.</span> <span class="nav-text">根据本地缓存</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#客户端负载"><span class="nav-number">5.3.</span> <span class="nav-text">客户端负载</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Zookeeper-其他优势及问题"><span class="nav-number">6.</span> <span class="nav-text">Zookeeper 其他优势及问题</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结"><span class="nav-number">7.</span> <span class="nav-text">总结</span></a></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2016 - 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">crossoverJie</span>
</div>

<div class="powered-by">
  Powered by <a class="theme-link" href="http://hexo.io">Hexo</a>
</div>

<div class="theme-info">
  Theme -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

        

<div class="busuanzi-count">

  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv"><i class="fa fa-user"></i><span class="busuanzi-value" id="busuanzi_value_site_uv"></span>人数</span>
  

  
    <span class="site-pv">您是第<span class="busuanzi-value" id="busuanzi_value_site_pv"></span>位童鞋</span>
  
  
</div>



        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  



  

    <script type="text/javascript">
      var disqus_shortname = 'crossoverjie';
      var disqus_identifier = '2018/08/27/distributed/distributed-discovery-zk/';
      var disqus_title = "分布式(一) 搞定服务注册与发现";
      var disqus_url = 'http://crossoverjie.top/2018/08/27/distributed/distributed-discovery-zk/';

      function run_disqus_script(disqus_script){
        var dsq = document.createElement('script');
        dsq.type = 'text/javascript';
        dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/' + disqus_script;
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
      }

      run_disqus_script('count.js');
      
        run_disqus_script('embed.js');
      
    </script>
  




  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
       search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();

    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
    'use strict';
    $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
            // get the contents from search data
            isfetched = true;
            $('.popup').detach().appendTo('.header-inner');
            var datas = $( "entry", xmlResponse ).map(function() {
                return {
                    title: $( "title", this ).text(),
                    content: $("content",this).text(),
                    url: $( "url" , this).text()
                };
            }).get();
            var $input = document.getElementById(search_id);
            var $resultContent = document.getElementById(content_id);
            $input.addEventListener('input', function(){
                var matchcounts = 0;
                var str='<ul class=\"search-result-list\">';                
                var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                $resultContent.innerHTML = "";
                if (this.value.trim().length > 1) {
                // perform local searching
                datas.forEach(function(data) {
                    var isMatch = true;
                    var content_index = [];
                    var data_title = data.title.trim().toLowerCase();
                    var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                    var data_url = data.url;
                    var index_title = -1;
                    var index_content = -1;
                    var first_occur = -1;
                    // only match artiles with not empty titles and contents
                    if(data_title != '' && data_content != '') {
                        keywords.forEach(function(keyword, i) {
                            index_title = data_title.indexOf(keyword);
                            index_content = data_content.indexOf(keyword);
                            if( index_title < 0 && index_content < 0 ){
                                isMatch = false;
                            } else {
                                if (index_content < 0) {
                                    index_content = 0;
                                }
                                if (i == 0) {
                                    first_occur = index_content;
                                }
                            }
                        });
                    }
                    // show search results
                    if (isMatch) {
                        matchcounts += 1;
                        str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                        var content = data.content.trim().replace(/<[^>]+>/g,"");
                        if (first_occur >= 0) {
                            // cut out 100 characters
                            var start = first_occur - 20;
                            var end = first_occur + 80;
                            if(start < 0){
                                start = 0;
                            }
                            if(start == 0){
                                end = 50;
                            }
                            if(end > content.length){
                                end = content.length;
                            }
                            var match_content = content.substring(start, end);
                            // highlight all keywords
                            keywords.forEach(function(keyword){
                                var regS = new RegExp(keyword, "gi");
                                match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                            });
                            
                            str += "<p class=\"search-result\">" + match_content +"...</p>"
                        }
                        str += "</li>";
                    }
                })};
                str += "</ul>";
                if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
                if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
                $resultContent.innerHTML = str;
            });
            proceedsearch();
        }
    });}

    // handle and trigger popup window;
    $('.popup-trigger').mousedown(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };

    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>

  

  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("Qv6ckEtL1pe3PJD10qoOLKtg-gzGzoHsz", "NXiHFodQfmI8oxkK6IThhjrF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script type="text/javascript" src="/js/src/particle.js" count="50" zindex="-2" opacity="1" color="0,104,183"></script>
</body>
</html>
